﻿using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NLog.Web;
using System;
using System.IO;
using System.Security.Authentication;
using VisionCloud.Utility;
using VisionCloud.Utility.Security;

namespace VisionCloud.Web
{
    public class Program
    {
        public static void Main(string[] args)
        {
            NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
            var host = CreateHostBuilder(args).Build();
            host.Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args)
                  .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                  .ConfigureLogging((hostingContext, logging) =>
                  {
                      foreach (ServiceDescriptor serviceDescriptor in logging.Services)
                      {
                          if (serviceDescriptor.ImplementationType == typeof(Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider))
                          {
                              logging.Services.Remove(serviceDescriptor);
                              break;
                          }
                      }
                    
                      logging.AddNLogWeb();
                      logging.AddNLog("nlog.config");
                  })
                   .ConfigureWebHostDefaults(WebHostBuilder =>
                   {
                       //  WebHostBuilder.UseUrls($"http://*:{ConfigHelper.GetAppSettingsValue<int>("HttpPort")}");
                       WebHostBuilder.UseKestrel(options =>
                       {
                           var httpsPort = ConfigHelper.GetValue<int>("HttpsPort");
                           options.ListenAnyIP(httpsPort, listenOptions =>
                           {
                               listenOptions.Protocols = HttpProtocols.Http1AndHttp2;

                               string certFile = ConfigHelper.GetValue<string>("cert_file");
                               string certPassword = AesCoreHelper.Decrypt(ConfigHelper.GetValue<string>("cert_password"), AesCoreHelper.Sceret);
                               //当服务器不联网时，CA证书会导致HTTPS握手失败，使用自签名代替
                               if (!string.IsNullOrEmpty(certFile) && !string.IsNullOrEmpty(certPassword))
                               {
                                   listenOptions.UseHttps(certFile, certPassword, serverOptions =>
                                   {
                                       serverOptions.SslProtocols = SslProtocols.Tls12;
                                   });
                               }
                               else
                               {
                                   listenOptions.UseHttps("bzlrobot.com.pfx", "bzlrobot.com", serverOptions =>
                                   {
                                       serverOptions.SslProtocols = SslProtocols.Tls12;
                                   });
                               }
                           });

                           options.ListenAnyIP(ConfigHelper.GetValue<int>("HttpPort"), listenOptions => { });

                           options.Limits.MaxRequestBodySize = null;

                           int timeOutMinutes = ConfigHelper.GetValue<int>("TimeOutMinutes");
                           options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(timeOutMinutes);
                           options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(timeOutMinutes);
                       }).UseStartup<Startup>()
                         .UseWebRoot(Directory.GetCurrentDirectory() + "/wwwroot");
                   });
        }
    }
}